package com.atguigu.day04;

import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.streaming.api.functions.source.SourceFunction;
import org.apache.flink.streaming.api.watermark.Watermark;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

// 侧输出流的概念
public class Example4 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        SingleOutputStreamOperator<String> result = env
                .addSource(new SourceFunction<String>() {
                    @Override
                    public void run(SourceContext<String> ctx) throws Exception {
                        ctx.collectWithTimestamp("atguigu", 1000L);
                        Thread.sleep(1000L);
                        ctx.emitWatermark(new Watermark(999L));
                        Thread.sleep(1000L);
                        ctx.collectWithTimestamp("atguigu", 500L);
                        Thread.sleep(1000L);
                        ctx.collectWithTimestamp("atguigu", 2000L);
                        Thread.sleep(1000L);
                    }

                    @Override
                    public void cancel() {

                    }
                })
                .process(new ProcessFunction<String, String>() {
                    @Override
                    public void processElement(String value, Context ctx, Collector<String> out) throws Exception {
                        if (ctx.timestamp() < ctx.timerService().currentWatermark()) {
                            ctx.output(
                                    // 侧输出流中的元素类型是String
                                    // 侧输出标签是单例
                                    new OutputTag<String>("late-element") {
                                    },
                                    "迟到数据的事件时间是：" + ctx.timestamp() // 向侧输出流发送的数据
                            );
                        } else {
                            out.collect("数据未迟到，它的事件时间是：" + ctx.timestamp() + "，此时水位线是：" + ctx.timerService().currentWatermark());
                        }
                    }
                });

        result.print("主流：");
        result.getSideOutput(new OutputTag<String>("late-element") {
        }).print("侧输出流：");

        env.execute();
    }
}
